//
//  NBAClubManagerDept.swift
//  Sports
//
//  Created by tiger on 2017/10/16.
//  Copyright © 2017年 Meigabay. All rights reserved.
//

import UIKit

/// 俱乐部管理部门
public class NBAClubManagerDept: NBADepartment {
    
    private lazy var clubs = [NBAClub]()
    
    init() {
        self.clubs = NBADBManager.shared.allClubs()
    }
    
    /// 所有俱乐部 除去玩家自身俱乐部
    ///
    /// - Returns: 俱乐部数组
    public func otherClubs() -> [NBAClub] {
        var tClubs = [NBAClub]()
        for club in self.clubs {
            if club.clubId != NBAUser.shared.club.clubId {
                tClubs.append(club)
            }
        }
        return tClubs
    }
    
    /// 创建一家俱乐部
    ///
    /// - Parameter club: 俱乐部
    public func createClub(club: NBAClub) throws -> NBAClub {
        //生成俱乐部ID
        club.clubId = String(format: "club_%0.0f",NSDate().timeIntervalSince1970*1000)
        club.createTime = NSDate().timeIntervalSince1970
        //创建俱乐部boss ,总经理 ，教练 ，球员
        let boss = NBAClubBoss()
        boss.clubId = club.clubId
        boss.name = "艾尔克林顿"
        boss.nickname = "小土豪"
        boss.avatar = "boss_avatar"
        boss.birthDay = 64037532
        boss.type = .boss
        let coach = NBAClubCoach()
        coach.clubId = club.clubId
        coach.name = "波波"
        coach.nickname = "波波不维奇"
        coach.avatar = "boss_avatar"
        coach.birthDay = 64037532
        coach.type = .coach
        do {
            try NBADBManager.shared.insertClub(club: club)
            try NBADBManager.shared.insertClubBoss(boss: boss)
            try NBADBManager.shared.insertClubCoach(coach: coach)
        } catch {
            throw(error)
        }
        return club
    }
    

    /// 从数据库获取俱乐部
    ///
    /// - Parameter clubId: 俱乐部ID
    /// - Returns: 俱乐部
    public func getClubById(clubId: String) -> NBAClub? {
        return NBADBManager.shared.filter(clubId: clubId)
    }
}
